package com.action;

import com.dao.mapper.StudentMapper;
import com.model.Student;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.service.RandomStudent;

/*
* 编程式事务管理
* 不使用spring TransactionTemplate模板
*
* */

@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:springmybatis.xml"})
public class TxTransactionNoTemplate {

    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springmybatis.xml");
    StudentMapper studentMapper = (StudentMapper) applicationContext.getBean("studentMapper");
    PlatformTransactionManager txManager = (PlatformTransactionManager)applicationContext.getBean("transactionManager");

    static final Logger logger = Logger.getLogger(TxTransactionNoTemplate.class.getName());

    static Student student = new RandomStudent().getStudent();

//    @Resource
//    private PlatformTransactionManager txManager;

    @Test
    public void curdTest(){


        //定义事务隔离级别，传播行为，
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();

        //定义隔离规则
        def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
        //定义传播行为（运行方式，在什么地方运行）
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        //获取事务状态 事务状态类，通过PlatformTransactionManager的getTransaction方法根据事务定义获取；获取事务状态后，Spring根据传播行为来决定如何开启事务
        TransactionStatus status = txManager.getTransaction(def);

        student = new RandomStudent().getStudent();

        try{
            studentMapper.insertOne(student);
//            int i = 1/0;
            //sma.selectOne(33);
            //sma.updateOne(student);
            studentMapper.insertOne(student);
            //提交
            txManager.commit(status);
        }catch (RuntimeException e){
            //回滚
            txManager.rollback(status);
        }

    }


}
